<template>
  <DesktopLayout v-if="data.show">
    <template #head>
      <DesignHead :title="title">
        <template #steps
          ><a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </template>
        <template #buttons>
          <div class="design-button">
            <a-button :disabled="current == 0 || spinning" class="common-button" @click="prev">{{
              t('上一步')
            }}</a-button>
            <a-button
              :disabled="current == steps.length - 1 || spinning"
              class="common-button"
              @click="next"
              >{{ t('下一步') }}</a-button
            >
            <a-button
              :class="current == 0 ? '' : 'common-todo-button'"
              :disabled="current == 0 || spinning"
              @click="onSave(false)"
              >{{ t('暂存') }}</a-button
            >
            <a-button
              type="primary"
              :disabled="current == 0 || spinning"
              class="common-button"
              @click="onSave(true)"
              >{{ t('保存') }}</a-button
            >
            <a-button type="primary" class="clean-icon" @click="$emit('close')">{{
              t('关闭')
            }}</a-button>
          </div>
        </template>
      </DesignHead>
    </template>
    <Basic v-if="current == 0" ref="basic" :basicData="data.basicData" />
    <Design v-if="current == 1" ref="design" @preview="onPreview" :list="data.list" />
    <LoadingBox v-if="spinning" />
    <DesktopPreview
      v-if="preview.show"
      ref="previewRef"
      :list="preview.list"
      @close="preview.show = false"
    />
  </DesktopLayout>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue';
  import { addDesktop, editDesktop, getDesktopInfo } from '/@/api/desktop/index';
  import DesignHead from './designer/layout/Head.vue';
  import DesktopLayout from './designer/layout/Desktop.vue';
  import Design from './designer/Design.vue';
  import Basic from './designer/Basic.vue';
  import DesktopPreview from './DesktopPreview.vue';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { DesktopBasicData, DesktopInfoItem } from '/@/model/desktop/designer';
  import { message } from 'ant-design-vue';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  let emits = defineEmits(['close']);
  const props = withDefaults(
    defineProps<{
      editId: string;
    }>(),
    {
      editId: '',
    },
  );
  const steps = [
    {
      title: t('基本配置'),
      content: t('基本配置'),
    },
    {
      title: t('桌面设计'),
      content: t('桌面设计'),
    },
  ];
  const basic = ref();
  const design = ref();
  const previewRef = ref();
  const current = ref<number>(0);
  const preview: {
    list: Array<DesktopInfoItem>;
    show: boolean;
  } = reactive({
    list: [],
    renderKey: 0,
    show: false,
  });
  const spinning = ref<boolean>(false);
  const data: {
    show: boolean;
    basicData: DesktopBasicData;
    jsonContent: string;
    list: Array<DesktopInfoItem>;
  } = reactive({
    show: false,
    basicData: {
      code: '', //编码
      name: '', //名称
      icon: '', //图标
      parentId: '', //上级
      sortCode: 0, //排序
      isFirst: 0, //首屏
      isMenu: 0, //菜单
      remark: '', //描述
      backgroundUrl: '', //封面图片
      systemId: '', // 系统主键
    },
    jsonContent: '',
    list: [],
  });

  const title = computed(() => {
    return props.editId ? '编辑桌面设计' : t('新增桌面设计');
  });
  onMounted(async () => {
    if (props.editId) {
      let { jsonContent, ...otherInfo } = await getDesktopInfo(props.editId);
      data.jsonContent = jsonContent;
      data.basicData = otherInfo;
      data.list = JSON.parse(jsonContent);
      data.show = true;
    } else {
      data.show = true;
    }
  });
  const next = async () => {
    if (current.value == 0) {
      let validate = await basic.value.validateForm();
      if (validate) {
        data.basicData = basic.value.getBasicData();
        current.value++;
      }
    }
  };
  const prev = async () => {
    data.list = await design.value.saveDesignData(false);
    current.value--;
  };
  function onPreview() {
    preview.list = design.value.getDesignData();
    preview.show = true;
  }
  async function onSave(close: boolean) {
    spinning.value = true;
    setTimeout(() => {
      save(close);
    }, 100);
  }
  async function save(close: boolean) {
    try {
      let { list, backgroundUrl } = await design.value.saveDesignData();
      data.jsonContent = JSON.stringify(list);
      data.basicData.backgroundUrl = backgroundUrl;
    } catch (error) {}

    try {
      let res = false;
      if (data.basicData.id) {
        res = await editDesktop({ ...data.basicData, jsonContent: data.jsonContent });
      } else {
        res = await addDesktop({ ...data.basicData, jsonContent: data.jsonContent });
      }
      if (res) {
        if (data.basicData.isFirst) {
          const permissionStore = usePermissionStore();
          await permissionStore.changePermissionCode();
        }
        if (close) {
          message.success(t('保存成功'));
          emits('close');
        } else {
          message.success(t('编辑成功'));
        }
      }
      spinning.value = false;
    } catch (error) {
      spinning.value = false;
    }
  }
</script>

<style lang="less" scoped>
  .head {
    height: 56px;
    width: 100%;
    box-shadow: 0 3px 6px 1px rgb(0 0 0 / 16%);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }

  .design-containers {
    position: fixed;
    inset: 0;
    z-index: 999;
    background-color: #f5f5f5;
  }

  [data-theme='dark'] .flow-containers {
    background-color: #151515;
  }

  .common-button {
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .common-todo-button {
    background-color: #ff8000;
    border-color: #ff8000;
    color: #fff;
  }

  .clean-icon {
    background-color: @clear-color;
    border-color: @clear-color;
  }

  .layout {
    position: relative;
    width: 100%;
    height: 100%;
    top: 56px;
  }

  :deep(.ant-steps) {
    width: 280px;
  }

  .design-button {
    display: flex;
    margin: 0 20px;
  }
</style>
